package com.atguigu.spzx.cloud.order.service.impl;

import com.atguigu.spzx.cloud.order.entity.Order;
import com.atguigu.spzx.cloud.order.entity.User;
import com.atguigu.spzx.cloud.order.mapper.OrderMapper;
import com.atguigu.spzx.cloud.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;


//todo 使用注册中心拉取 [单纯的拉取服务列表,没有负载均衡]
//@Service
public class OrderServiceImpl拉取没有负载均衡  {

    //@Autowired
    private OrderMapper orderMapper ;

    //@Autowired
    private RestTemplate restTemplate;

    //@Autowired
    private DiscoveryClient discoveryClient; //提供拉取服务的方法

    //@Override
    public Order findOrderByOrderId(Long orderId) {
        Order order = orderMapper.findOrderByOrderId(orderId);
        //远程调用获取user对象

        List<ServiceInstance> instances = discoveryClient.getInstances("spzx-cloud-user");
        //ServiceInstance == 每个服务信息  服务的ip地址 以及服务的port
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();//ip地址部分
        int port = serviceInstance.getPort(); //port地址部分
        User user = restTemplate.getForObject("http://"+host+":"+port+"/api/user/findUserByUserId/"+order.getUserId(), User.class);
        order.setUser(user);
        return order;
    }

}